package com.chat.datea.fragment;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chat.datea.R;
import com.chat.datea.adapter.FindFragment_Jump_ListView_Adapter;
import com.chat.datea.base.BaseFragment;
import com.chat.datea.bean.JumpEntity;
import com.chat.datea.bean.SongInfos;
import com.chat.datea.utils.cache.MyConfig;
import com.chat.datea.utils.download.CommonProgressDialog;
import com.chat.datea.utils.volley.VolleySingleton;
import com.google.gson.Gson;

import java.io.File;


/**
 * 发现页面点击KTV跳转到得fragment
 *
 * Created by dllo on 15/10/23.
 */
public class FindJumpFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private ListView find_Jump;
    private FindFragment_Jump_ListView_Adapter adapter;
    private VolleySingleton singleton;
    private ImageButton find_Back;
    private AlertDialog alertDialog;
    private AlertDialog.Builder builder;
    private JumpEntity jumpEntity;
    private CommonProgressDialog progressDialog;
    String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.learn.detail&page_no=0&page_size=50&query=all&value=0&desc=KTV%E7%83%AD%E6%AD%8C%E6%A6%9C";


    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initView() {
        find_Jump = (ListView) view.findViewById(R.id.find_Jump);
        singleton = VolleySingleton.getVolleySingleton(mActivity);
        find_Back = (ImageButton) view.findViewById(R.id.find_Back);
        find_Back.setOnClickListener(this);
        find_Jump.setOnItemClickListener(this);
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_find_songlist_jump, null);
        return view;
    }

    /**
     * 解析数据并传递数据
     **/
    public void getData() {
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                //解析实体类
                 jumpEntity = gson.fromJson(response, JumpEntity.class);
                jumpEntity.getResult().getItems();

                adapter = new FindFragment_Jump_ListView_Adapter(mActivity, jumpEntity);
                find_Jump.setAdapter(adapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        singleton.addQueue(request, "tag");

    }

    @Override
    public void onClick(View v) {
        //点击返回上一级fragment
        getActivity().getSupportFragmentManager().popBackStack();
    }
    /**
     * KTV 页面 点击监听事件
     * **/
    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        alertDialog = null;
        builder = null;
        builder = new AlertDialog.Builder(getActivity());
        alertDialog = builder.setTitle("系统提示是否下载")
                .setMessage(jumpEntity.getResult().getItems().get(position).getSong_title())
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(mActivity, "已取消下载", Toast.LENGTH_SHORT).show();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        /**
                         * 下载
                         * **/
                        String song_id = jumpEntity.getResult().getItems().get(position).getSong_id();
                        Log.i("SONGID", "++++" + song_id);
                        String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json" +
                                "&songid=" +
                                song_id +
                                "&ts=1445582673704&e=Yv077YWCp4kyKb%2FthNHwKwMq52TU6BhTuyXiIob13Do%3D&nw=2&ucf=1&res=1&l2p=0&lpb=&usup=1&lebo=0";

                        //解析数据
                        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Gson gson = new Gson();
                                SongInfos down = gson.fromJson(response, SongInfos.class);
                                String show_link = down.getSongurl().getUrl().get(0).getFile_link();
                                String song_title = down.getSonginfo().getTitle();
                                /**弹出进度条**/
                                progressDialog = new CommonProgressDialog(mActivity, handler);
                                progressDialog.setMax(down.getSongurl().getUrl().get(0).getFile_size());
                                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                progressDialog.show();
                                progressDialog.setName(song_title, down.getSonginfo().getAuthor());

                                //得到的数据存入缓存
                                MyConfig.putSharePre(mActivity, "link", "url", show_link);
                                MyConfig.putSharePre(mActivity, "album", "title", song_title);
                                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                    Environment.getExternalStorageDirectory().getPath();
                                    //获得父类里的方法
                                    progressDialog.download(show_link, new File("/mnt/sdcard/Download/"));

                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        });
                        singleton.addQueue(request, "tag");

                    }
                }).create();
        alertDialog.show();
    }
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == 200){
                progressDialog.dismiss();
                Log.i("Sysout", "handleMessage_200 ");
            }
            return false;
        }
    }) ;
}
